package com.xmh.reptile.util;

import com.xmh.reptile.service.NovelService;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.util.Date;

public class DownloadUtil {

    public static void download(String url, String dir) {

        try {
            Thread.sleep(2000);
            URL httpurl = new URL(url);
            String fileName = getFileNameFromUrl(url);
            System.out.println(fileName);
            File f = new File(dir + NovelService.simpleDateFormat.format(new Date()) + ".txt");

            if (!f.exists()) {
                boolean newFile = f.createNewFile();
            }
            FileUtils.copyURLToFile(httpurl, f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getFileNameFromUrl(String url) {
        String name = new Long(System.currentTimeMillis()).toString() + ".X";
        int index = url.lastIndexOf("/");
        if (index > 0) {
            name = url.substring(index + 1);
            if (name.trim().length() > 0) {
                return name;
            }
        }
        return name;
    }

}
